package com.dong.webMagic.pipeline;

import com.alibaba.fastjson.JSONObject;
import com.dong.common.lang.DateUtils;
import com.dong.webMagic.dao.NewsMapper;
import com.dong.webMagic.model.News;
import org.apache.ibatis.session.SqlSession;
import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.pipeline.Pipeline;

import java.util.Date;
import java.util.Map;

/**
 * 自定义实现Pipeline接口
 */
public class HupuNewsPipeline implements Pipeline {

    private SqlSession sqlSession;

    public HupuNewsPipeline(SqlSession sqlSession) {
        this.sqlSession = sqlSession;
    }

    @Override
    public void process(ResultItems resultitems, Task task) {
        Map<String, Object> mapResults = resultitems.getAll();
        if (mapResults.size() == 0) {
            return;
        }
        News news = new News();
        news.setId((String) mapResults.get("id"));
        news.setType((String) mapResults.get("type"));
        news.setTitle((String) mapResults.get("title"));
        news.setContent((String) mapResults.get("content"));
        news.setCreateTime(DateUtils.parseDate(mapResults.get("createTime")));
        news.setUpdateTime(new Date());
        System.out.println(Thread.currentThread().getName() + "   news:[" + JSONObject.toJSONString(news) + "]");
        System.out.println("================================================================");
        // 从mybatis中得到dao对象
        NewsMapper newsMapper = sqlSession.getMapper(NewsMapper.class);
        News dbNews = newsMapper.findById(news.getId());
        if (dbNews == null) {
            newsMapper.insert(news);
        } else {
            newsMapper.update(news);
        }
        sqlSession.commit();
    }
}
